package com.SmartCampus.system.controller;

import com.SmartCampus.system.annotation.AuthCheck;
import com.SmartCampus.system.common.BaseResponse;
import com.SmartCampus.system.common.DeleteRequest;
import com.SmartCampus.system.common.ErrorCode;
import com.SmartCampus.system.common.ResultUtils;
import com.SmartCampus.system.constant.UserConstant;
import com.SmartCampus.system.exception.BusinessException;
import com.SmartCampus.system.exception.ThrowUtils;
import com.SmartCampus.system.model.dto.clazz.ClazzAddRequest;
import com.SmartCampus.system.model.dto.clazz.ClazzQueryRequest;
import com.SmartCampus.system.model.dto.clazz.ClazzUpdateRequest;
import com.SmartCampus.system.model.entity.Clazz;
import com.SmartCampus.system.service.ClazzService;
import com.SmartCampus.system.service.CourseService;
import com.SmartCampus.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 班级接口
 *
 * @author wangliang
 */
@RestController
@RequestMapping("/clazz")
@Slf4j
@Api(tags = "班级接口")
public class ClazzController {

    @Resource
    private ClazzService clazzService;

    @Resource
    private UserService userService;

    @Resource
    private CourseService courseService;

    // region 增删改查

    /**
     * 创建班级（仅管理员）
     *
     * @param clazzAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "创建班级（仅管理员）")
    public BaseResponse<Long> addClazz(@RequestBody ClazzAddRequest clazzAddRequest, HttpServletRequest request) {
        if (clazzAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Clazz clazz = new Clazz();
        BeanUtils.copyProperties(clazzAddRequest, clazz);
        boolean result = clazzService.save(clazz);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(clazz.getId());
    }

    /**
     * 删除班级（仅管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除班级（仅管理员）")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能为空");
        }
        boolean result = clazzService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 更新班级（仅管理员）
     *
     * @param clazzUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新班级（仅管理员）")
    public BaseResponse<Boolean> updateUser(@RequestBody ClazzUpdateRequest clazzUpdateRequest) {
        if (clazzUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能小于等于0");
        }
        QueryWrapper<Clazz> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", clazzUpdateRequest.getId());
        Clazz clazz = clazzService.getOne(queryWrapper);
        if (clazzUpdateRequest.getName() == null || clazzUpdateRequest.getName().equals("")) {
            clazzUpdateRequest.setName(clazz.getName());
        }
        if (clazzUpdateRequest.getNumber() == null || clazzUpdateRequest.getNumber() <= 0) {
            clazzUpdateRequest.setNumber(clazz.getNumber());
        }
        if (clazzUpdateRequest.getIntroduction() == null || clazzUpdateRequest.getIntroduction().equals("")) {
            clazzUpdateRequest.setIntroduction(clazz.getIntroduction());
        }
        if (clazzUpdateRequest.getHeadmaster() == null || clazzUpdateRequest.getHeadmaster().equals("")) {
            clazzUpdateRequest.setHeadmaster(clazz.getHeadmaster());
        }
        if (clazzUpdateRequest.getPhone() == null || clazzUpdateRequest.getPhone().equals("")) {
            clazzUpdateRequest.setPhone(clazz.getPhone());
        }
        BeanUtils.copyProperties(clazzUpdateRequest, clazz);
        boolean result = clazzService.updateById(clazz);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 分页获取班级列表（仅管理员）
     *
     * @param clazzQueryRequest
     * @return
     */
    @PostMapping("/get/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "分页获取全部班级列表（仅管理员）")
    public BaseResponse<Page<Clazz>> listClazzByPage(@RequestBody ClazzQueryRequest clazzQueryRequest) {
        long current = clazzQueryRequest.getCurrent() == 0 ? 1 : clazzQueryRequest.getCurrent();
        long size = clazzQueryRequest.getPageSize() == 0 ? 10 : clazzQueryRequest.getPageSize();
        Page<Clazz> page = new Page<>(current, size);
        Page<Clazz> clazzPage = clazzService.getAll(page, clazzQueryRequest);
        if (clazzPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(clazzPage);
    }

    /**
     * 分页获取我的班级列表(仅学生)
     *
     * @param clazzQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/student")
    @ApiOperation(value = "分页获取我的班级列表(仅学生)")
    public BaseResponse<Page<Clazz>> listClazzByStudent(@RequestBody ClazzQueryRequest clazzQueryRequest, HttpServletRequest request) {
        if (clazzQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long clazzId = userService.getLoginUser(request).getClazzId();
        long current = clazzQueryRequest.getCurrent() == 0 ? 1 : clazzQueryRequest.getCurrent();
        long size = clazzQueryRequest.getPageSize() == 0 ? 10 : clazzQueryRequest.getPageSize();

        Page<Clazz> page = new Page<>(current, size);
        Page<Clazz> clazzPage = clazzService.getStudent(page, clazzQueryRequest, clazzId);
        if (clazzPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(clazzPage);
    }
    // endregion
}
